package cn.tannn.ops.logs.controller;


import cn.tannn.jdevelops.annotations.web.mapping.PathRestController;
import cn.tannn.jdevelops.jpa.result.JpaPageResult;
import cn.tannn.jdevelops.jpa.select.EnhanceSpecification;
import cn.tannn.jdevelops.jwt.standalone.util.JwtWebUtil;
import cn.tannn.jdevelops.result.response.ResultPageVO;
import cn.tannn.ops.logs.controller.dto.LoginLogPage;
import cn.tannn.ops.logs.controller.dto.LoginLogUserPage;
import cn.tannn.ops.logs.entity.LoginLog;
import cn.tannn.ops.logs.service.LoginLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * 登录日志
 *
 * @author <a href="https://tannn.cn/">tan</a>
 * @date 2024/4/8 10:58
 */
@PathRestController("/log/login")
@Tag(name = "登录日志")
@Slf4j
@RequiredArgsConstructor
public class LoginLogController {

    private final LoginLogService loginLogService;

    @Operation(summary = "查询登录日志")
    @PostMapping("page")
    public ResultPageVO<LoginLog, JpaPageResult<LoginLog>> findPage(@RequestBody @Valid LoginLogPage page) {
        Page<LoginLog> customers = loginLogService.findPage(page, page.getPage());
        JpaPageResult<LoginLog> pageResult = JpaPageResult.toPage(customers);
        return ResultPageVO.success(pageResult, "查询成功");
    }

    @Operation(summary = "查询当前登录者的登录日志")
    @PostMapping("/user/page")
    public ResultPageVO<LoginLog,JpaPageResult<LoginLog>> findUserPage(@RequestBody @Valid LoginLogUserPage page
            , HttpServletRequest request) {
        String loginName = JwtWebUtil.getTokenSubjectExpires(request);
        Specification<LoginLog> find = EnhanceSpecification.beanWhere(page
                , e -> e.eq(true,"loginName", loginName));
        Page<LoginLog> customers  = loginLogService.getJpaBasicsDao().findAll(find, page.getPage().pageable());
        JpaPageResult<LoginLog> pageResult = JpaPageResult.toPage(customers);
        return ResultPageVO.success(pageResult, "查询成功");
    }

}

